﻿using System;
using System.Diagnostics;
using System.IO;

using CWare.CMetrics.Core;
using System.Reflection;

namespace CWare.CMetrics.Runner
{
//TODO: tests
class Program
{
    private const string FileExtension = ".cs";
    private static string GetPath(string[] args)
    {
        return args[0];
    }

    public static int Main(string[] args)
    {
        if (args.Length!=1)
        {
            System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
            string[] names = a.FullName.Split(',');

            string commandLine = Environment.CommandLine.Replace("\"", "");
            string testName = System.IO.Path.GetFileNameWithoutExtension(commandLine);

            if (string.Compare(names[0], testName, true) != 0)
            {
                Console.WriteLine("Dont rename me please...");
                return -1;
            }

            Console.WriteLine("usage: "+names[0]+" dir_to_scan");
            return -1;
        }
        ApplyScanToEveryCSFile(GetPath(args));
        return 0;
    }

    private static string[] GetSubDirectories(string path)
    {
        return Directory.GetDirectories(path);
    }
    private static string[] GetFiles(string path)
    {
        return Directory.GetFiles(path);
    }
    private static void ApplyScanToEveryCSFile(string path)
    {
        foreach (var file in GetFiles(path))
        {
            if ( ! file.EndsWith(FileExtension))
            {
                continue;
            }
            Console.WriteLine("" + file + ": ");
            try
            {
                var messagePattern = "SLOC:{0,4} ; ELOC:{1,4}";
                var message = string.Format(messagePattern, Metrics.SLOC(file), Metrics.ELOC(file));
                Console.WriteLine(message);
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("  cannot access file");
            }
        }


        foreach (var subDirectory in GetSubDirectories(path))
        {
            ApplyScanToEveryCSFile(subDirectory);
        }

    }


}
}